package top.hmtools.wxmp.core.httpclient.responseHandler;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用于进行回调的处理http response 
 * <br>输入流
 * @author HyboWork
 *
 */
public class ResponseHandlerInputStream implements ResponseHandler<InputStream> {
	
	private final Logger logger = LoggerFactory.getLogger(ResponseHandlerInputStream.class);

	@Override
	public InputStream handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		
		//缓存输入流，获取服务器返回的原始输入流
		InputStream contentInStream = response.getEntity().getContent();
		
		//获取临时目录
		File tempDirectory = FileUtils.getTempDirectory();
		if(!tempDirectory.exists()){
			tempDirectory.mkdirs();
		}
		
		//将网络输入流缓存到临时目录
		File tempFile = new File(tempDirectory.getPath()+File.separator+"hm"+File.separator+UUID.randomUUID());
		FileOutputStream cacheOutputStream = FileUtils.openOutputStream(tempFile);
		IOUtils.copy(contentInStream, cacheOutputStream);
		
		BufferedInputStream resulttBIS = new BufferedInputStream(FileUtils.openInputStream(tempFile));
		
		if(this.logger.isDebugEnabled()){
			this.logger.debug("http请求获取的响应状态码是：{}，临时缓存文件路径：{}",statusCode,tempFile);
		}
		if(statusCode >= 200 && statusCode <300){
			return resulttBIS;
		}else{
			String contentStr = IOUtils.toString(contentInStream,"UTF-8");
			throw new RuntimeException("http请求失败，响应状态码是："+statusCode+"，反馈的错误信息是："+contentStr);
		}
	}

}
